//Developed By Mudassar Raza
// MCS Semester-1

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include<graphics.h>
#include<iomanip.h>

#define max 4
int moves=0;
int a[max][max]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}};
int b[max][max]={{1,5,9,13},{2,6,10,14},{3,7,11,15},{4,8,12,0}};
int check()
{
   int i,j,flag = 0;
   for(i=0;i<max;i++)
       for(j=0;j<max;j++)
	    if(b[i][j]==a[i][j])
		flag=1;
   if(flag)
	return 1;
   return 0;
}
void show();

void main()
{
		      //     a[1][1]=55;
//=========================================================
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
errorcode = graphresult();
if (errorcode != grOk)
{
   printf("Graphics error: %s\n", grapherrormsg(errorcode));
   printf("Press any key to halt:");
   getch();
   exit(1);
}
setbkcolor(GREEN);
//=========================================================
   int i,j,temp;
   char ch;
   show();
   ch=getch();
   i=3; j=3;
   while((ch!=27)||(!check()))
      {
	 if(ch==72)     //up
	   {
	     if(j>=1)
	     {
	     temp=a[i][j-1];
	     a[i][j-1]=a[i][j];
	     a[i][j]=temp;
	     moves++;
	     j=j-1;
	     }
	   }
	 if(ch==80) //down
	   {
	    if(j<=max-2)
	     {
	     temp=a[i][j+1];
	     a[i][j+1]=a[i][j];
	     a[i][j]=temp;
	     moves++;
	     j=j+1;
	     }
	   }
	 if(ch==75)//left
	   {
	     if(i>=1)
	     {
	     temp=a[i-1][j];
	     a[i-1][j]=a[i][j];
	     a[i][j]=temp;
	     moves++;
	     i=i-1;
	     }
	   }
	 if(ch==77)//right
	   {
	     if(i<=max-2)
	     {
	     temp=a[i+1][j];
	     a[i+1][j]=a[i][j];
	     a[i][j]=temp;
	     moves++;
	     i=i+1;
	     }
	   }



	 show();
	 ch=getch();
      }

 getch();
}

void show()
{
   int x=10,y=10,i,j;
   char string[25];
   cleardevice();
 setcolor(RED);
   for(i=0;i<max;i++)
     {
      for(j=0;j<max;j++)
	{
	 rectangle(x+i*100,y+j*100,x+i*100+100,y+j*100+100);
	 if(a[i][j]!=0)
	 {
	 outtextxy(x+i*100+50,y+j*100+50,itoa(a[i][j],string,10));
	 }

	}
     }
     outtextxy(450,300,"moves : ");
     outtextxy(570,300,itoa(moves,string,10));
     outtextxy(50,450,"_____________________________press Esc to Quit________________________ ");
}